import BaseModel from './BaseModel'
import AccountModel from './AccountModel'
import { post, get } from '@/api/ajax'
import { DataApi } from '@/api/apis'
import { PageDataType, ListType } from './types'

class DataModel extends BaseModel{

  // 数据
  data = ''
  // 排序索引
  index = 0
  // 创建人
  createUser = new AccountModel()
  // 历史数据
  historyDatas: Array<DataModel> = []
  // 删除数据的API
  removeDataApi = DataApi.removeRecord
  // 当前数据对应的父类ID
  superId = ''

  setDataWithJson(json: {}) {
    super.setDataWithJson(json);
    this.createUser = AccountModel.creatModelWithJson(this.createUser)
  }
  // 设置数据
  setData(data: any) {
    if (!data) {
      return ''
    }
    this.data = typeof data === 'object' ? JSON.stringify(data) : `${data}`
  }

  // 获取单条数据
  async getOneData() {
    const data = await get<DataModel>(`${DataApi.getOne}/${this.superId}`)
    this.setDataWithJson(data)
  }

  // 设置单条数据
  async updateOneData(): Promise<string> {
    return await post<string>(`${DataApi.updateOne}/${this.superId}`, this.getJson('data', {
      createTime: this.createTime || undefined
    }))
  }

  // 获取历史记录
  static async record<T extends BaseModel>(id: string, pageData: PageDataType, other = {}): Promise<ListType<T>> {
    this.loadListApi = `${DataApi.recordList}/${id}`
    return this.loadModels<T>(pageData, other)
  }

  /**
   * 删除历史记录
   */
  removeRecordData(msg: string, other: {} = {}): Promise<unknown> {
    this.removeDataApi = DataApi.removeRecord
    return super.removeData(msg, other);
  }

  /**
   * 恢复历史记录数据
   */
  restoreOne() {
    return get(`${DataApi.restoreOne}/${this._id}`)
  }

  /**
   * 添加数组数据
   */
  addArrayData() {
    return post(`${DataApi.dataArrayPush}/${this.superId}`, this.getJson('data index'))
  }

  /**
   * 获取列表数据
   */
  static getDataArrayList<T extends BaseModel>(enumId: string, pageData: PageDataType, other = {}) {
    this.loadListApi = `${DataApi.dataArrayList}/${enumId}`
    return this.loadModels<T>(pageData, other)
  }

  /**
   * 更新列表中的数据
   */
  updateDataArr() {
    return post<DataModel>(`${DataApi.dataArrayUpdate}/${this._id}`, this.getJson('data index'))
  }

  /**
   * 更新列表中的数据
   */
  arrayListRecyclePush() {
    this.removeDataApi = DataApi.arrayListRecyclePush
    return this.removeData('确定要删除吗？')
  }

  /**
   * 更新列表中的数据
   */
  arrayListRecyclePop() {
    return get(`${DataApi.arrayListRecyclePop}/${this._id}`)
  }

  /**
   * 删除数据
   */
  removeDataWithRecord() {
    this.removeDataApi = DataApi.removeData
    return this.removeData('数据无价，会彻底删除数据及他的历史记录！考虑清楚哦')
  }

}

export default DataModel
